package com.cskaoyan.wx.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.FootPrintMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.service.UserManagementService;
import com.cskaoyan.wx.pojo.FootprintAndGoods;
import com.cskaoyan.wx.vo.FootprintVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author LiaoLong
 * @date 2021-05-12 20:28
 */
@Service
public class FootprintServiceImpl implements FootprintService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FootPrintMapper footPrintMapper;

    @Override
    public FootprintVO getFootprintByUsername(Integer page, Integer size, String username) {

        // 获取用户信息
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        assert users.size() <= 1;
        User user = users.get(0);
        Integer userId = user.getId();

        // 查询足迹
        PageHelper.startPage(page, size);
        List<FootprintAndGoods> footprintAndGoods = footPrintMapper.queryFootprintAndGoods(userId);

        List<FootprintVO.FootprintListBean> footprintList = new ArrayList<>();
        for (FootprintAndGoods footprintAndGood : footprintAndGoods) {
            Goods goods = footprintAndGood.getGoods();
            FootPrint footPrint = footprintAndGood.getFootPrint();

            String brief = goods.getBrief();
            String picUrl = goods.getPicUrl();
            String name = goods.getName();
            BigDecimal retailPrice = goods.getRetailPrice();
            Date addTime = footPrint.getAddTime();
            Integer goodsId = footPrint.getGoodsId();
            Integer id = footPrint.getId();
            FootprintVO.FootprintListBean footprintListBean = new FootprintVO.FootprintListBean(brief, picUrl, addTime, goodsId, name, id, retailPrice);
            footprintList.add(footprintListBean);
        }

        PageInfo<FootprintAndGoods> footprintAndGoodsPageInfo = new PageInfo<>(footprintAndGoods);
        long total = footprintAndGoodsPageInfo.getTotal();
        long totalPages = total / size;
        FootprintVO footprintVO = new FootprintVO(totalPages, footprintList);
        return footprintVO;
    }

    @Override
    public void deleteFootprint(Integer id) {
        FootPrint footPrint = new FootPrint();
        footPrint.setId(id);
        footPrint.setDeleted(true);
        footPrintMapper.updateByPrimaryKeySelective(footPrint);
    }
}
